<template>
  <div>
    <el-upload
      :before-upload="handleBeforeUpload"
      :limit="limit"
      name="file"
      :http-request="httpRequest"
      :show-file-list="false"
      :on-remove="handleRemove"
      :headers="headers"
      :disabled="disabled"
      :class="{hide: fileList.length >= limit}"
    >
            <slot>
            </slot>
    </el-upload>
  </div>


    <!-- 上传提示 -->
    <!-- <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div> -->

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      >
    </el-dialog>
</template>

<script>

import {useApi} from "@/composables/useApi.js";
import showTost from "@/components/toast/index.js";

export default {
  props: {
    value: [String, Object, Array],
    disabled:{
      type: Boolean,
      default: false
    },
    // 图片数量限制
    limit: {
      type: Number,
      default: 1
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 6
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    limitVo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VITE_API_BASE_URL + '/admin/Upload/upload', // 上传的图片服务器地址
      headers: {
        Authorization: useCookie('accessToken').value || ''
      },
      fileList: []
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    }
  },
  watch: {
    value: {
      handler(val) {
        console.log(val)
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',')
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === 'string') {
              item = {name: item, url: item}
            }
            return item
          })
        } else {
          this.fileList = []
          return []
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async httpRequest(param) {
      const formData = new FormData()
      formData.append('file', param.file) // 传入bpmn文件
      const {data} = await useApi('/admin/Upload/upload').post(formData)

      this.loading.close()
      if(data.value.status==200){
        showTost("上传成功", {duration: 3000, type: "success"})
        this.$emit('input', data.value.data)
      }else{
        showTost("上传失败", {duration: 3000, type: "error"})
      }
    },
    // 删除图片
    handleRemove(file, fileList) {
      if(this.disabled)return
      this.$emit('input', '')
    },
    // 上传前loading加载
    handleBeforeUpload(file) {

      if (this.fileSize) {
        let isLt = false
        if (this.limitVo.unit === 'KB') {
          isLt = file.size / 1024 < this.fileSize
          if (!isLt) {
            this.$message.error(`上传图片大小不能超过${this.fileSize}KB!`)
            return false
          }
        } else {
          isLt = file.size / 1024 / 1024 < this.fileSize
          if (!isLt) {
            this.$message.error(`上传图片大小不能超过 ${this.fileSize} MB!`)
            return false
          }
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    // 上传失败
    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      })
      this.loading.close()
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = ''
      separator = separator || ','
      for (const i in list) {
        strs += list[i].url + separator
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : ''
    }
  }
}
</script>
<style lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}

// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}

.component-upload-image2 {
  .el-upload-list--picture-card {
    width: 100%;
    margin: 0;
    padding: 0;
  }

  ::v-deep .el-upload--picture-card {
    width: 100%;
    height: 160px;
    object-fit: cover;
    margin: 0;
    border: none;
    background: #fff !important;
    line-height: 0 !important;
    text-align: left;
    margin-left: 15px;
  }

  .hide {
    .el-upload--picture-card {
      display: none;
    }
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 600px !important;
    height: 160px;
    object-fit: cover;
    margin: 0;
  }
}

.photo-box {
  width: 100%;
  height: 160px;
  border: 1px dashed #ccc;
  border-radius: 8px;
  background-image: url("@/assets/avatar.png");
  background-size: cover;
  background-position: center;

  .inner-box {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .6);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .upload-btn {
      width: 40px;
      height: 40px;
      background-color: #fff;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .text {
      font-size: 13px;
      font-weight: 400;
      color: #F0EFF0;
    }
  }
}
.el-upload{
  .el-upload-dragger{
    padding: 0!important;
  }
}

</style>
